package com.jingwu.example.graphql;

import com.coxautodev.graphql.tools.GraphQLMutationResolver;
import com.jingwu.example.pojo.dto.BookDTO;
import com.jingwu.example.pojo.entity.AuthorDO;
import com.jingwu.example.pojo.entity.BookDO;
import com.jingwu.example.pojo.entity.CategoryDO;
import com.jingwu.example.repo.AuthorRepository;
import com.jingwu.example.repo.BookRepository;
import com.jingwu.example.repo.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.deepexi.web.support.pojo.converter.utils.ConverterUtils.convert;

/**
 * @author jingwu
 * @since 2021/2/1
 */
@Service
public class BookMutationResolver implements GraphQLMutationResolver {

    private final BookRepository repository;
    private final CategoryRepository categoryRepository;
    private final AuthorRepository authorRepository;

    @Autowired
    public BookMutationResolver(BookRepository repository, CategoryRepository categoryRepository, AuthorRepository authorRepository) {
        this.repository = repository;
        this.categoryRepository = categoryRepository;
        this.authorRepository = authorRepository;
    }

    public Integer saveBook(BookDTO dto) {
        BookDO entity = convert(dto, BookDO.class);

        AuthorDO author = convert(dto.getAuthor(), AuthorDO.class);
        authorRepository.insert(author);

        CategoryDO category = convert(dto.getCategory(), CategoryDO.class);
        categoryRepository.insert(category);

        entity.setAuthorId(author.getId());
        repository.insert(entity);
        return entity.getId();
    }

    public Boolean updateBook(Integer id, BookDTO dto) {
        BookDO entity = convert(dto, BookDO.class);
        entity.setId(id);
        return repository.update(entity);
    }
}
